/**
 * 
 */
package com.vision.core.sv.util;

import java.sql.BatchUpdateException;
import java.sql.SQLException;

import org.hibernate.JDBCException;
import org.springframework.dao.DataAccessException;

/**
 * Utility class for database-related operations.
 * 
 * @author Mark
 *
 */
public class DB {
	
	/**
	 * Tries to get the {@link SQLException} instance from the specified <tt>e</tt>.
	 * If <tt>e</tt> does not contain an {@link SQLException}, this returns null.
	 * 
	 * @param e
	 * @return
	 */
	public static SQLException getSQLException(Throwable e) {
		// If e is a DataAccessException (wrapper from Spring)
		if (e instanceof DataAccessException) {
			if (e.getCause() instanceof JDBCException) {
				JDBCException jdbce = (JDBCException) e.getCause();
				if (jdbce.getCause() instanceof BatchUpdateException) {
					BatchUpdateException bue = (BatchUpdateException) jdbce.getCause();
					return bue.getNextException();
				} else if (jdbce.getCause() instanceof SQLException) {
					return (SQLException) jdbce.getCause();
				}
			}
		}
		else {
			Throwable t = e;
			while (t != null && !(t instanceof SQLException))
				t = t.getCause();
			return (SQLException) t;
		}
		return null;
	}

}
